// 合约配置
const CONTRACT_ADDRESS = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
const NETWORK_ID = 88;

// 全局变量
let web3;
let contract;
let userAccount;
let contractABI;

// 页面加载完成后初始化
window.addEventListener('load', async () => {
    // 加载ABI
    try {
        const response = await fetch('abi.json');
        contractABI = await response.json();
        init();
    } catch (error) {
        console.error('Failed to load ABI:', error);
        showToast('加载合约ABI失败', 'error');
    }
});

// 初始化函数
async function init() {
    // 绑定事件
    document.getElementById('connectWallet').addEventListener('click', connectWallet);
    document.getElementById('createProjectForm').addEventListener('submit', createProject);
    
    // 绑定过滤器按钮
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
            e.target.classList.add('active');
            loadProjects(e.target.dataset.filter);
        });
    });
    
    // 绑定标签页按钮
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            e.target.classList.add('active');
            loadMyProjects(e.target.dataset.tab);
        });
    });
    
    // 模态框关闭按钮
    document.querySelector('.close').addEventListener('click', () => {
        document.getElementById('projectModal').style.display = 'none';
    });
    
    // 点击模态框外部关闭
    window.onclick = (event) => {
        const modal = document.getElementById('projectModal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    };
    
    // 检查是否已安装MetaMask
    if (typeof window.ethereum !== 'undefined') {
        // 获取MetaMask provider
        const provider = WalletHelper.getMetaMaskProvider();
        
        if (provider) {
            web3 = new Web3(provider);
            
            // 监听账户变化
            provider.on('accountsChanged', (accounts) => {
            if (accounts.length > 0) {
                userAccount = accounts[0];
                updateWalletInfo();
                loadAllData();
            } else {
                userAccount = null;
                updateWalletInfo();
            }
            });
            
            // 监听网络变化
            provider.on('chainChanged', () => {
                window.location.reload();
            });
            
            // 自动连接（如果之前已授权）
            const accounts = await web3.eth.getAccounts();
            if (accounts.length > 0) {
                userAccount = accounts[0];
                await setupContract();
                updateWalletInfo();
                loadAllData();
            }
        } else {
            // 显示检测到的钱包
            const wallets = WalletHelper.detectWallets();
            if (wallets.length > 0) {
                showToast(`检测到 ${wallets.join(', ')}，请安装MetaMask`, 'warning');
            } else {
                showToast('请安装MetaMask钱包', 'error');
            }
        }
    } else {
        showToast('请安装MetaMask钱包', 'error');
    }
}

// 连接钱包
async function connectWallet() {
    try {
        showLoader();
        
        // 强制使用MetaMask
        const provider = await WalletHelper.forceMetaMaskConnection();
        
        // 请求连接钱包
        const accounts = await provider.request({ method: 'eth_requestAccounts' });
        userAccount = accounts[0];
        
        // 使用MetaMask provider
        web3 = new Web3(provider);
        
        // 检查网络
        const chainId = await web3.eth.getChainId();
        if (chainId != NETWORK_ID) {
            showToast(`请切换到正确的网络 (Chain ID: ${NETWORK_ID})`, 'error');
            hideLoader();
            return;
        }
        
        // 设置合约
        await setupContract();
        
        // 更新UI
        updateWalletInfo();
        loadAllData();
        
        showToast('MetaMask连接成功', 'success');
    } catch (error) {
        console.error('连接钱包失败:', error);
        if (error.message) {
            showToast(error.message, 'error');
        } else {
            showToast('连接钱包失败', 'error');
        }
    } finally {
        hideLoader();
    }
}

// 设置合约实例
async function setupContract() {
    contract = new web3.eth.Contract(contractABI, CONTRACT_ADDRESS);
}

// 更新钱包信息显示
async function updateWalletInfo() {
    const addressDiv = document.getElementById('walletAddress');
    const balanceDiv = document.getElementById('walletBalance');
    const connectBtn = document.getElementById('connectWallet');
    
    if (userAccount) {
        // 显示地址
        addressDiv.textContent = `${userAccount.substring(0, 6)}...${userAccount.substring(38)}`;
        
        // 获取余额
        const balance = await web3.eth.getBalance(userAccount);
        const ethBalance = web3.utils.fromWei(balance, 'ether');
        balanceDiv.textContent = `${parseFloat(ethBalance).toFixed(4)} ETH`;
        
        // 更新按钮
        connectBtn.style.display = 'none';
    } else {
        addressDiv.textContent = '';
        balanceDiv.textContent = '';
        connectBtn.style.display = 'block';
    }
}

// 加载所有数据
async function loadAllData() {
    loadProjects('all');
    loadMyProjects('created');
}

// 创建项目
async function createProject(e) {
    e.preventDefault();
    
    if (!userAccount) {
        showToast('请先连接钱包', 'error');
        return;
    }
    
    const title = document.getElementById('projectTitle').value;
    const description = document.getElementById('projectDescription').value;
    const goalAmount = document.getElementById('goalAmount').value;
    const duration = document.getElementById('duration').value;
    
    try {
        showLoader();
        
        // 转换为秒
        const durationInSeconds = duration * 3600;
        // 转换为wei
        const goalInWei = web3.utils.toWei(goalAmount, 'ether');
        
        // 调用合约创建项目
        await contract.methods.createProject(
            title,
            description,
            goalInWei,
            durationInSeconds
        ).send({ from: userAccount });
        
        showToast('项目创建成功', 'success');
        
        // 清空表单
        document.getElementById('createProjectForm').reset();
        
        // 重新加载项目列表
        loadAllData();
    } catch (error) {
        console.error('创建项目失败:', error);
        showToast('创建项目失败', 'error');
    } finally {
        hideLoader();
    }
}

// 加载项目列表
async function loadProjects(filter = 'all') {
    if (!contract) return;
    
    try {
        showLoader();
        
        const projectCount = await contract.methods.getTotalProjects().call();
        const projectsDiv = document.getElementById('projectsList');
        projectsDiv.innerHTML = '';
        
        for (let i = 0; i < projectCount; i++) {
            const project = await contract.methods.projects(i).call();
            
            // 根据过滤条件显示项目
            if (filter === 'all' || getStatusName(project.status).toLowerCase() === filter) {
                const projectCard = createProjectCard(i, project);
                projectsDiv.appendChild(projectCard);
            }
        }
    } catch (error) {
        console.error('加载项目失败:', error);
        showToast('加载项目失败', 'error');
    } finally {
        hideLoader();
    }
}

// 加载我的项目
async function loadMyProjects(tab) {
    if (!contract || !userAccount) return;
    
    try {
        showLoader();
        
        const projectsDiv = document.getElementById('myProjectsList');
        projectsDiv.innerHTML = '';
        
        if (tab === 'created') {
            // 获取我创建的项目
            const myProjects = await contract.methods.getUserCreatedProjects(userAccount).call();
            
            for (const projectId of myProjects) {
                const project = await contract.methods.projects(projectId).call();
                const projectCard = createProjectCard(projectId, project);
                projectsDiv.appendChild(projectCard);
            }
        } else {
            // 获取我投资的项目
            const myContributions = await contract.methods.getUserParticipatedProjects(userAccount).call();
            
            for (const projectId of myContributions) {
                const project = await contract.methods.projects(projectId).call();
                const contribution = await contract.methods.getUserContribution(projectId, userAccount).call();
                const projectCard = createProjectCard(projectId, project, contribution);
                projectsDiv.appendChild(projectCard);
            }
        }
    } catch (error) {
        console.error('加载我的项目失败:', error);
        showToast('加载我的项目失败', 'error');
    } finally {
        hideLoader();
    }
}

// 创建项目卡片
function createProjectCard(projectId, project, contribution = null) {
    const card = document.createElement('div');
    card.className = 'project-card';
    card.onclick = () => showProjectDetail(projectId);
    
    const progress = (project.currentAmount / project.goalAmount) * 100;
    const statusName = getStatusName(project.status);
    const statusClass = getStatusClass(project.status);
    
    const endTime = new Date((parseInt(project.startTime) + parseInt(project.duration)) * 1000);
    const timeLeft = getTimeLeft(endTime);
    
    card.innerHTML = `
        <div class="project-header">
            <h3 class="project-title">${project.title}</h3>
            <span class="project-status ${statusClass}">${statusName}</span>
        </div>
        <p class="project-description">${project.description}</p>
        <div class="progress-bar">
            <div class="progress-fill" style="width: ${Math.min(progress, 100)}%"></div>
        </div>
        <div class="project-stats">
            <span>进度: ${progress.toFixed(2)}%</span>
            <span>${web3.utils.fromWei(project.currentAmount, 'ether')} / ${web3.utils.fromWei(project.goalAmount, 'ether')} ETH</span>
        </div>
        <div class="project-stats">
            <span>投资人数: ${project.contributorCount}</span>
            <span>${timeLeft}</span>
        </div>
        ${contribution ? `<div class="project-stats"><span>我的投资: ${web3.utils.fromWei(contribution, 'ether')} ETH</span></div>` : ''}
    `;
    
    return card;
}

// 显示项目详情
async function showProjectDetail(projectId) {
    if (!contract) return;
    
    try {
        showLoader();
        
        const project = await contract.methods.projects(projectId).call();
        const contributors = await contract.methods.getProjectContributors(projectId).call();
        
        const modal = document.getElementById('projectModal');
        const modalContent = document.getElementById('modalContent');
        
        const progress = (project.currentAmount / project.goalAmount) * 100;
        const statusName = getStatusName(project.status);
        const statusClass = getStatusClass(project.status);
        
        const endTime = new Date((parseInt(project.startTime) + parseInt(project.duration)) * 1000);
        const timeLeft = getTimeLeft(endTime);
        
        let contributorsList = '';
        for (const contributor of contributors) {
            const amount = await contract.methods.getUserContribution(projectId, contributor).call();
            contributorsList += `
                <div class="contributor-item">
                    <span>${contributor.substring(0, 6)}...${contributor.substring(38)}</span>
                    <span>${web3.utils.fromWei(amount, 'ether')} ETH</span>
                </div>
            `;
        }
        
        modalContent.innerHTML = `
            <div class="project-detail">
                <div class="detail-header">
                    <h2 class="detail-title">${project.title}</h2>
                    <div class="detail-meta">
                        <span class="project-status ${statusClass}">${statusName}</span>
                        <span>创建者: ${project.creator.substring(0, 6)}...${project.creator.substring(38)}</span>
                        <span>创建时间: ${new Date(project.startTime * 1000).toLocaleDateString()}</span>
                    </div>
                </div>
                
                <div class="detail-description">
                    <h3>项目描述</h3>
                    <p>${project.description}</p>
                </div>
                
                <div class="detail-stats">
                    <div class="stat-box">
                        <div class="stat-value">${web3.utils.fromWei(project.currentAmount, 'ether')} ETH</div>
                        <div class="stat-label">当前金额</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-value">${web3.utils.fromWei(project.goalAmount, 'ether')} ETH</div>
                        <div class="stat-label">目标金额</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-value">${progress.toFixed(2)}%</div>
                        <div class="stat-label">完成进度</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-value">${project.contributorCount}</div>
                        <div class="stat-label">投资人数</div>
                    </div>
                </div>
                
                <div class="detail-time">
                    <h3>时间信息</h3>
                    <p>截止时间: ${endTime.toLocaleString()}</p>
                    <p>剩余时间: ${timeLeft}</p>
                </div>
                
                ${contributors.length > 0 ? `
                    <div class="detail-contributors">
                        <h3>投资者列表</h3>
                        <div class="contributors-list">
                            ${contributorsList}
                        </div>
                    </div>
                ` : ''}
                
                <div class="action-buttons">
                    ${project.status == 0 && userAccount ? `
                        <div class="contribute-form">
                            <input type="number" id="contributeAmount" placeholder="投资金额 (ETH)" step="0.0001" min="0.0001">
                            <button class="btn btn-primary" onclick="contributeToProject(${projectId})">投资</button>
                        </div>
                    ` : ''}
                    
                    ${project.creator.toLowerCase() === userAccount?.toLowerCase() ? `
                        ${project.status == 0 ? `
                            <button class="btn btn-danger" onclick="cancelProject(${projectId})">取消项目</button>
                        ` : ''}
                        ${project.status == 1 ? `
                            <button class="btn btn-success" onclick="withdrawFunds(${projectId})">提取资金</button>
                        ` : ''}
                    ` : ''}
                    
                    ${project.status == 2 && userAccount ? `
                        <button class="btn btn-warning" onclick="claimRefund(${projectId})">申请退款</button>
                    ` : ''}
                </div>
            </div>
        `;
        
        modal.style.display = 'block';
    } catch (error) {
        console.error('加载项目详情失败:', error);
        showToast('加载项目详情失败', 'error');
    } finally {
        hideLoader();
    }
}

// 投资项目
async function contributeToProject(projectId) {
    const amount = document.getElementById('contributeAmount').value;
    if (!amount || parseFloat(amount) <= 0) {
        showToast('请输入有效的投资金额', 'error');
        return;
    }
    
    try {
        showLoader();
        
        const amountInWei = web3.utils.toWei(amount, 'ether');
        
        await contract.methods.contribute(projectId).send({
            from: userAccount,
            value: amountInWei
        });
        
        showToast('投资成功', 'success');
        
        // 关闭模态框并刷新数据
        document.getElementById('projectModal').style.display = 'none';
        loadAllData();
    } catch (error) {
        console.error('投资失败:', error);
        showToast('投资失败', 'error');
    } finally {
        hideLoader();
    }
}

// 取消项目
async function cancelProject(projectId) {
    if (!confirm('确定要取消这个项目吗？')) return;
    
    try {
        showLoader();
        
        await contract.methods.cancelProject(projectId).send({ from: userAccount });
        
        showToast('项目已取消', 'success');
        
        document.getElementById('projectModal').style.display = 'none';
        loadAllData();
    } catch (error) {
        console.error('取消项目失败:', error);
        showToast('取消项目失败', 'error');
    } finally {
        hideLoader();
    }
}

// 提取资金
async function withdrawFunds(projectId) {
    if (!confirm('确定要提取资金吗？')) return;
    
    try {
        showLoader();
        
        await contract.methods.withdrawFunds(projectId).send({ from: userAccount });
        
        showToast('资金提取成功', 'success');
        
        document.getElementById('projectModal').style.display = 'none';
        loadAllData();
    } catch (error) {
        console.error('提取资金失败:', error);
        showToast('提取资金失败', 'error');
    } finally {
        hideLoader();
    }
}

// 申请退款
async function claimRefund(projectId) {
    if (!confirm('确定要申请退款吗？')) return;
    
    try {
        showLoader();
        
        await contract.methods.requestRefund(projectId).send({ from: userAccount });
        
        showToast('退款成功', 'success');
        
        document.getElementById('projectModal').style.display = 'none';
        loadAllData();
    } catch (error) {
        console.error('申请退款失败:', error);
        showToast('申请退款失败', 'error');
    } finally {
        hideLoader();
    }
}

// 辅助函数：获取状态名称
function getStatusName(status) {
    const statusNames = ['进行中', '已成功', '已失败', '已提取'];
    return statusNames[status] || '未知';
}

// 辅助函数：获取状态样式类
function getStatusClass(status) {
    const statusClasses = ['status-active', 'status-successful', 'status-failed', 'status-withdrawn'];
    return statusClasses[status] || '';
}

// 辅助函数：计算剩余时间
function getTimeLeft(endTime) {
    const now = new Date();
    const diff = endTime - now;
    
    if (diff <= 0) return '已结束';
    
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    
    if (days > 0) return `剩余 ${days} 天 ${hours} 小时`;
    if (hours > 0) return `剩余 ${hours} 小时`;
    
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    return `剩余 ${minutes} 分钟`;
}

// 显示加载提示
function showLoader() {
    document.getElementById('loader').style.display = 'block';
}

// 隐藏加载提示
function hideLoader() {
    document.getElementById('loader').style.display = 'none';
}

// 显示消息提示
function showToast(message, type = 'info') {
    const toast = document.getElementById('toast');
    toast.textContent = message;
    toast.className = `toast ${type}`;
    toast.style.display = 'block';
    
    setTimeout(() => {
        toast.style.display = 'none';
    }, 3000);
}